package com.strongbj.iot.devices.dam.response.handle.v1;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.dam.message.DAMMessage;
import com.strongbj.iot.devices.dam.message.MQMessageOfDAM;
import com.strongbj.iot.devices.dam.request.entity.ScreenCommandEntity;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

public class ScreenToServerCommandHandle extends DAMV1Handle {
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private static Logger logger = LogManager.getLogger(ScreenToServerCommandHandle.class.getName());
	private static final byte COMMAND = Integer.valueOf("FE", 16).byteValue();
	private static final String TOPIC = "damCommandToService";
	private static final String ACTION_CODE = "screenRequest";
	private static final String DEV_TYPE = "damDc";
	private DAMMessage globalDAMMessage; // 全局DAM变量，相互处理类传值

	public ScreenToServerCommandHandle(DAMMessage damMsg) {
		this.globalDAMMessage = damMsg;
	}

	@Override
	protected boolean isHandleDAMMessage(DAMMessage t) {
		if (t.getCommand() == COMMAND) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, DAMMessage t) {
		this.message2Service(t); // 将消息传到服务端
		return null;
	}

	/**
	 * 将收到的消息转到服务端
	 * 
	 * @param t
	 */
	private void message2Service(DAMMessage t) {
		String command = ByteUtil.byteArrToHexString(t.getDatas());
		
		if(command.replace("0", "").length()==0) return; // 如果返回的数据全是0，则不处理
		
		MQMessageOfDAM msg = new MQMessageOfDAM();
		msg.setActioncode(ACTION_CODE);
		ScreenCommandEntity result = new ScreenCommandEntity();
		result.setCommand(command);

		// TODO 如果传回来的getAddressCode设备编号为000001，就采用心跳处理里赋值的全局变量中的设备编号
		if (t.getAddressCode()[0] == (byte) 0x0 && t.getAddressCode()[1] == (byte) 0x0
				&& t.getAddressCode()[2] == (byte) 0x1 && this.globalDAMMessage != null) {
			result.setRackConverCode(ByteUtil.byteArrToHexString(this.globalDAMMessage.getAddressCode()));
		} else {
			result.setRackConverCode(ByteUtil.byteArrToHexString(t.getAddressCode()));
		}
		msg.setAwsPostdata(result);
		msg.setDevType(DEV_TYPE);
		msg.setTimestamp(ByteUtil.bytesToLong(t.getSn()));
		String json = JSON.toJSONString(msg);
		logger.info("DAM设备 向MQ发送屏幕命令数据	 JSON={}", json);
		topicSender.send(TOPIC, json);
	}
}